package com.poizon.infrastructure.idem.core.exception;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.apache.dubbo.rpc.filter.ExceptionFilter;

@Slf4j
@Activate(group = {CommonConstants.PROVIDER, CommonConstants.CONSUMER})
public class GlobalExceptionFilter extends ExceptionFilter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        try {
            // 调用下一个过滤器链
            Result invoke = invoker.invoke(invocation);

            if (invoke.hasException()) {
                throw invoke.getException();
            }
            return invoke;
        } catch (Throwable t) {
            // 处理异常
            return handleException(t);
        }
    }

    private Result handleException(Throwable t) {
        if (t instanceof RuntimeException) {
            // todo: 幂等存储告警
            boolean idempotentDbStoreException = t.getMessage().contains("IdempotentDbStoreException");
            if (idempotentDbStoreException) {
                log.error(StrUtil.format(">幂等存储异常"), t);
            }
            return new AppResponse(t);
        }

        if (t instanceof RpcException) {
            // 处理RpcException

        } else {
            // 处理其他异常

        }
        return null;
    }

}
